// 渠道
var tblChannel;
var tableData = {};

$(document).ready(function () {
    // 输入有效性验证
    $("#flagCreateForm , #flagEditForm").validate({
        debug:true,
        errorPlacement: function(error, element)
        {
            error.insertAfter(element);
        }
    });
    
    $.extend($.validator.defaults,{ignore:""}); //隐藏控件也校验，去掉此行不验证隐藏控件   
	
    // 渠道list
	tblChannel = $('#tblChannel').DataTable({
        "processing": true,
        "serverSide": true,
        "lengthMenu" : [ [ 10, 25, 50, 100, 500, 1000 ], [ 10, 25, 50, 100, 500, 1000] ],
        "dom": '<"bottom"rtflp>',
        "searching": false,
        "pagingType": "full_numbers",
        "deferRender": true,
        "ajax": {
            "url": "/channel/getChannelList.action",
            "data": function ( d ) {
                d.quickSearch = encodeURI($('#quickSearch').val());
            },
            "dataFilter": function(data) {
                var json = jQuery.parseJSON(data);
                tableData = json.data.reduce(function(a, b) {
                    a[b.channelId] = b;
                    return a;
                }, {});
                return JSON.stringify(json);
            }
        },
        "tableTools": {
            "sRowSelect": "bootstrap"
        },
        "columns": [
            {"data": "channelCode"},
            {"data": "channelName"},
            {"data": "project"},
            {"data": "createTime"},
            {"data": "updateTime"},
            {"data": "remark"},
            {"mRender": function(data, type, row) {
                return '<button data-id="' + row.channelId + '" type="button" class="btn btn-info btn-xs btn-channel-edit"><i class="fa fa fa-edit"></i>修改</button> \
                <button data-id="' + row.channelId + '" type="button" class="btn btn-danger btn-xs btn-channel-delete"><i class="fa fa-trash-o"></i>删除</button>'}}
        ],
        "columnDefs": [
        	{"className": "truncate-text tooltip-column-detail", "targets":[1]},
            {"className": "truncate-text tooltip-column-detail", "targets":[2]},
            {"className": "truncate-text tooltip-column-detail", "targets":[5]}
        ],
        "order": [[ 0, "asc" ]]
    });

    
    // 文字过长截断显示悬浮框
    $("#tblChannel").tooltip({
        selector: ".tooltip-column-detail",
        container: "body",
        title: function() {
            if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                return $(this).text();
            }
        }
    });
    
    // 注册删除事件
	$("#tblChannel").on("click", ".btn-channel-delete", function() {
		var id = $(this).data("id"), data = tableData[id];
        window.top.window.showModalConfirm("确定要删除渠道吗？", function() {
        	var loading = window.top.window.getIndexBusyOverlay();
        	$.ajax({
                type:"POST",
                url:"/channel/deleteChannel.action?channelId=" + id,
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                async: false,//同步
                beforeSend:function(){
                    if(loading) {
                    	loading.settext("正在处理中，请稍后...");
                    }
                },
                success:function(data) {
                	loading.remove();
                	if (data.success == "Y") {
                        window.top.window.showScoMessage('ok', '删除成功');
                        tblChannel.draw();
                    } else{
                        window.top.window.showModalAlert(data.errormessage);
                    }
                },
                error:function(XMLHttpRequest, textStatus) {
                	loading.remove();
                    if (XMLHttpRequest.status == 500) {
                        var result = eval("(" + XMLHttpRequest.responseText + ")");
                        alert(result.errorObject.errorText);
                    }
                }
            });
        });
	});
	
	// 初始化项目列表
    $.ajax({
        type: "GET",
        url: "/projectManager/getAllAvailableProjects.action",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async: true,// 异步
        success: function (data) {
            if (data.result == "success") {
                $("#form-project option").remove();
                $("#form-projectEdit option").remove();
                $("#form-project").append("<option value=''>请选择</option>");
                $("#form-projectEdit").append("<option value=''>请选择</option>");
                $.each(data.data, function (n, value) {
                    $("#form-project").append("<option value='" + value.prjId + "'>" + value.prjName + "</option>");
                    $("#form-projectEdit").append("<option value='" + value.prjId + "'>" + value.prjName + "</option>");
                });
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });

	
	// 添加按钮
	// 创建品牌保存按钮点击事件绑定
	$("#add-channel").click(function(){

		// 父窗体归还本页的编辑对话框
		window.top.window.returnCustomModalDialog();

		// 输入有效性验证
		if(!$("#channelCreateForm").valid()) {
			// 父窗体借用本页的编辑对话框
			window.top.window.borrowCustomModalDialog($("#create-channel-form"));
			return false;
		}
		//保存分担规则
		var channelCode = $("#form-channel-code").val();
		var channelName = $("#form-channel-name").val();
		var projectCode= $("#form-project").val();
		var projectName= $("#form-project").find("option:selected").text();
		var remark = $("#form-remark").val();

		var params = {};  
		params.channelCode = channelCode;  
		params.channelName = channelName;
		params.projectCode= projectCode;
		params.project= projectName;
		params.remark = remark;
		var loading = window.top.window.getIndexBusyOverlay();
		$.ajaxSettings['contentType'] = "application/x-www-form-urlencoded; charset=utf-8";
	    $.ajax({
	        type: "POST",
	        url:"/channel/createChannel.action",
	        data: JSON.stringify(params),
	        contentType: "application/json;charset=utf-8",
	        dataType: "json",
	        beforeSend:function(){
	            if(loading) {
	            	loading.settext("正在处理中，请稍后...");
	            }
	        },
	        success:function(data) {
	        	loading.remove();
				if (data.success == "Y") {
					$('#create-channel-form').modal('hide');
					window.top.window.showScoMessage('ok', '创建成功');
					tblChannel.draw();
				} else{
					window.top.window.showModalAlert(data.errormessage);
					window.top.window.borrowCustomModalDialog($("#create-channel-form"));
				}
			},
			error:function(XMLHttpRequest, textStatus) {
				loading.remove();
				if (XMLHttpRequest.status == 500) {
					var result = eval("(" + XMLHttpRequest.responseText + ")");
					alert(result.errorObject.errorText);
				}
			}
	    });
	});

	// 创建分单规则保存按钮点击事件绑定
	$("#edit-channel").click(function(){

		// 父窗体归还本页的编辑对话框
		window.top.window.returnCustomModalDialog();

		// 输入有效性验证
		if(!$("#channelEditForm").valid()) {
			// 父窗体借用本页的编辑对话框
			window.top.window.borrowCustomModalDialog($("#edit-channel-form"));
			return false;
		}
		//保存分担规则
		var channelId = $("#edit-channel-form").attr("channelId");
		var channelCode = $("#form-channel-codeEdit").val();
		var channelName = $("#form-channel-nameEdit").val();
		var projectCode = $("#form-projectEdit").val();
		var projectName = $("#form-projectEdit").find("option:selected").text();
		var remark = $("#form-remarkEdit").val();

		var params = {};  
		params.channelCode = channelCode;  
		params.channelName = channelName;
		params.channelId = channelId;
		params.projectCode = projectCode;
		params.project = projectName;
		params.remark = remark;
		
		$.ajaxSettings['contentType'] = "application/x-www-form-urlencoded; charset=utf-8";
		var loading = window.top.window.getIndexBusyOverlay();
		$.ajax({
	        type: "POST",
	        url:"/channel/updateChannel.action",
	        data: JSON.stringify(params),
	        contentType: "application/json;charset=utf-8",
	        dataType: "json",
	        beforeSend:function(){
	            if(loading) {
	            	loading.settext("正在处理中，请稍后...");
	            }
	        },
	        success:function(data) {
	        	loading.remove();
				if (data.success == "Y") {
					$('#edit-channel-form').modal('hide');
					window.top.window.showScoMessage('ok', '修改成功');
					tblChannel.draw();
				} else{
					window.top.window.showModalAlert(data.errormessage);
					window.top.window.borrowCustomModalDialog($("#edit-channel-form"));
				}
			},
			error:function(XMLHttpRequest, textStatus) {
				loading.remove();
				if (XMLHttpRequest.status == 500) {
					var result = eval("(" + XMLHttpRequest.responseText + ")");
					alert(result.errorObject.errorText);
				}
			}
	    });
	});

	// 创建品牌对话框关闭事件发生
	$('#create-channel-form').on('hide.bs.modal', function () {
		// 父窗体归还本页的编辑对话框
		window.top.window.returnCustomModalDialog();
	});
	
	// 创建分单规则对话框关闭事件发生
	$('#edit-channel-form').on('hide.bs.modal', function () {
		// 父窗体归还本页的编辑对话框
		window.top.window.returnCustomModalDialog();
	});
	
	// 渠道编辑事件
	$("#tblChannel").on("click", ".btn-channel-edit", function() {
		$("#channelEditForm")[0].reset();
		var id = $(this).data("id"), data = tableData[id];
		// 初始化项目列表
		$.ajax({
			type:"GET",
			url:"/channel/channelDetail.action?channelId=" + id,
			contentType: "application/json;charset=utf-8",
			dataType: "json",
			async: false,//同步
			success:function(data) {
				if (data.result == "success") {
					$("#edit-channel-form").attr("channelId", id);
					$("#form-channel-codeEdit").val(data.data.channelCode);
					$("#form-channel-nameEdit").val(data.data.channelName);
					$("#form-projectEdit").val(data.data.projectCode);
					$("#form-remarkEdit").val(data.data.remark);
					// 父窗体借用本页的编辑对话框
					var editDialog = window.top.window.borrowCustomModalDialog($("#edit-channel-form"));
					editDialog.modal({show:true, backdrop:'static'});
				} else{
					window.top.window.showScoMessage('ok', data.errormessage);
				}
			},
			error:function(XMLHttpRequest, textStatus) {
				if (XMLHttpRequest.status == 500) {
					var result = eval("(" + XMLHttpRequest.responseText + ")");
					alert(result.errorObject.errorText);
				}
			}
		});
	});
});

// 快速搜索
$("#btnQuickSearch").click(function () {
	tblChannel.draw();
});

// 搜索框的回车事件
$('#quickSearch').keydown(function(e){
    if(e.keyCode==13){
        $("#btnQuickSearch").click();
    }
});

// 下载渠道
$("#downloadChannel").click(function () {
	$.ajaxSettings['contentType'] = "application/x-www-form-urlencoded; charset=utf-8";

    $.ajax({
        type: "POST",
        url: "/channel/downloadChannel.action",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (data) {
            if (data.result == "success") {
                window.top.window.showScoMessage('ok', '下载成功');
                tblChannel.draw();
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
});

// 刷新
function refresh() {   
	$('#quickSearch').val("");
	tblChannel.draw();
}

/**
 * 打开创建的对话框
 * @returns
 */
function newChannel() {
	$("#channelCreateForm")[0].reset();

	var editDialog = window.top.window.borrowCustomModalDialog($("#create-channel-form"));
	editDialog.modal({show:true, backdrop:'static'});
}
